'use strict';
const db = uniCloud.database();
const usersCollection = db.collection('user');

exports.main = async (event, context) => {
	const {
		avatarUrl,
		nickName,
		code
	} = event;
	if (!nickName || nickName == '' || nickName == undefined) {
		return {
			errCode: 1,
			errMsg: "参数nickName不能为空"
		}
	}

	if (!code || code == '' || code == undefined) {
		return {
			errCode: 1,
			errMsg: "参数code不能为空"
		}
	}

	const openRes = await uniCloud.request({
		url: "https://api.weixin.qq.com/sns/jscode2session",
		data: {
			appid: "wx5c175dbb9263e7bf",
			secret: "85335c040e8e8eebf30f0c2c10eab7b5",
			js_code: code,
			grant_type: "authorization_code"
		}
	})
	// console.log('openRes', openRes)
	var openId = ""
	if (openRes.statusCode === 200 && openRes.data && openRes.data.openid) {
		openId = openRes.data.openid
	} else {
		return {
			errCode: -1,
			errMsg: '获取登录信息失败'
		}
	}

	try {
		// 查询用户是否已存在
		const a = await usersCollection.where({
			openId: openId
		}).get();
		// console.log('a',a)
		// 云函数API查询没有result
		let userList = a.data
		const currentTime = Date.now();

		let result;
		if (userList && userList.length > 0) {
			let userData = {
				lastLoginTime: currentTime
			};
			// 用户已存在，更新信息
			result = await usersCollection
				.doc(userList[0]._id)
				.update(userData);

			return {
				errCode: 0,
				errMsg: '登录成功',
				data: {
					userId: userList[0]._id,
					avatarUrl:userList[0].avatarUrl,
					nickName:userList[0].nickName
				}
			};
		} else {
			// 用户不存在，创建新用户
			let userData = {
				avatarUrl,
				nickName,
				openId,
				createTime: currentTime
			};
			const addResult = await usersCollection.add(userData);

			// 删除openId
			delete userData.openId

			return {
				errCode: 0,
				errMsg: '创建成功',
				data: {
					userId: addResult.id,
					avatarUrl:avatarUrl,
					nickName:nickName
				}
			};
		}
	} catch {
		return {
			errCode: -1,
			errMsg: '服务器错误',
		};
	}
};